<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
class Specs extends Backend_Controller {
	public $id;
	
	/**
	 * 构造函数
	 */
	public function __construct() {
		parent::__construct ();
		$this->isValidRequest ();
		// 加载Specs模型
		$this->load->model ( 'backend/Specs_model', 'Specs' );
	}
	
	/**
	 * 商品规格列表
	 */
	public function index() {
		$this->id = intval ( $this->input->post_get ( 'id' ) );
		if ($this->id < 1) {
			$this->renderJson ( 10005 );
		}
		$data = $this->Specs->getAll ( $this->id, $this->page, $this->input->post () );
		$data ['id'] = $this->id;
		$this->load->view ( 'backend/specs/index', $data );
	}
	
	/**
	 * 添加规格
	 */
	public function add() {
		$this->id = intval ( $this->input->post_get ( 'id' ) );
		if ($this->id < 1) {
			$this->renderJson ( 10005 );
		}
		if ($this->isPost ()) {
			$spec = $this->post ( 'multiSpecs' );
			$specs = array ();
			if (! empty ( $spec )) {
				foreach ( $spec as $val ) {
					if (!empty($val ['spec']) && !empty($val['price'])) {
						$specs [] = array('spec' => $val ['spec'], 'price' => $val['price'] * 100, 'stock' => $val['stock']);
					}
				}
				$result = $this->Specs->addSpecs ( $this->id, $specs );
				if ($result) {
					$this->renderJson ( 200, '', array (
							'navTabId' => 'backendspecsindex',
							'callbackType' => 'closeCurrent' 
					) );
				}
			}
			$this->renderJson ( 300 );
		}
		
		$data ['id'] = $this->id;
		$this->load->view ( 'backend/specs/add', $data );
	}
	
	/**
	 * 删除规格
	 */
	public function delete() {
		$ids = $this->input->post_get ( 'ids' );
		if ($this->Specs->deleteSpecs ( $ids )) {
			$this->renderJson ( 200, '', array (
					'navTabId' => 'backendspecsindex' 
			) );
		}
		
		$this->renderJson ( 300 );
	}
	
	/**
	 * 修改规格信息
	 */
	public function edit() {
		if ($this->isPost ()) {
			$this->load->library('form_validation');
			$this->form_validation->validateData ( array (
					'id',
					'spec',
				'price',
				'stock',
			), array (
					array (
							'id',
							'integer|greater_than[0]' 
					),
					array (
							'spec',
							'required' 
					),
				array (
							'price',
							'required|integer' 
					),
				array (
							'stock',
							'required|integer' 
					)
			) );
			
			if ($this->form_validation->hasErrors ()) {
				$this->renderJson ( 300, $this->form_validation->error );
			}
			
			$data = array (
					'spec' => $this->form_validation->spec,
				'price' => $this->form_validation->price * 100,
				'stock' => $this->form_validation->stock,
			);
			if ($this->Specs->updateSpecs ( $data, $this->form_validation->id )) {
				$this->renderJson ( 200, '', array (
						'navTabId' => 'backendspecsindex',
						'callbackType' => 'closeCurrent' 
				) );
			}
			$this->renderJson ( 300 );
		}
		$id = intval ( $this->get ( 'id' ) );
		$data = $this->Specs->findSpecs ( $id );
		$this->load->view ( 'backend/specs/edit', $data );
	}
}